package com.foreknow.controller;

import com.foreknow.model.UserEntity;
import com.foreknow.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
public class MainController {
    @Autowired
    private UserRepository userRepository;
    @RequestMapping(value = "/admin/users",method = RequestMethod.GET)
    public String getUsers(ModelMap modelMap) {
        //调用持久层的方法来查询所有用户的信息
        List<UserEntity> list = userRepository.findAll();
        //将查询到的list保存到ModelMap中
        modelMap.addAttribute("list",list);
        return "admin/users";
    }

    @RequestMapping(value = "/admin/users/delete/{id}",method = RequestMethod.GET)
    public String deleteUser(@PathVariable("id") Integer userId){
        //根据删除
        userRepository.delete(userId);
        //刷新
        userRepository.flush();
        //重定向
     return "redirect:/admin/users";
    }

    @RequestMapping(value = "/admin/users/add",method = RequestMethod.GET)
    public String addUser() {
        return "admin/addUser";
    }

    @RequestMapping(value = "/admin/users/addP",method = RequestMethod.POST)
    public String addUserPost(@ModelAttribute("user") UserEntity userEntity) {
        //调用持久层的方法了
        userRepository.saveAndFlush(userEntity);
        return "redirect:/admin/users";
    }
}
